package me.firstapp.bbs.controller;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import me.firstapp.bbs.base.BaseController;
import me.firstapp.common.exception.ServiceException;
import me.firstapp.common.exception.StatusHouse;
import me.firstapp.common.json.ListObject;
import me.firstapp.common.json.PageObject;
import me.firstapp.common.json.SingleObject;
import me.firstapp.common.module.bbs.JsonMember;
import me.firstapp.common.module.shop.JsonCategory;
import me.firstapp.common.module.shop.JsonProduct;
import me.firstapp.common.module.shop.JsonProductSkuRelation;
import me.firstapp.common.module.shop.TempshoppingCart;
import me.firstapp.common.module.shop.TempshoppingCartItem;
import me.firstapp.common.utils.ResponseUtils;
import me.firstapp.common.utils.StrUtils;
import me.firstapp.spi.bbs.MemberService;
import me.firstapp.spi.shop.CategoryService;
import me.firstapp.spi.shop.ProductService;
import me.firstapp.spi.shop.ProductSkuRelService;

@Controller
@RequestMapping("/shop")
public class ShopController extends BaseController {

	@Autowired
	private ProductService productService;

	@Autowired
	private MemberService memberService;

	@Autowired
	private ProductSkuRelService productSkuRelService;

	@Autowired
	private CategoryService categoryService;

	@RequestMapping(value = "/index")
	public ModelAndView showShopIndex(
			@RequestParam(value = "pageNo", required = true, defaultValue = "1") Integer pageNo,
			@RequestParam(value = "pageSize", required = true, defaultValue = "20") Integer pageSize, Long categoryId,
			HttpServletRequest request, HttpServletResponse response, ModelMap modelMap) {
		// 商品种类
		ListObject<JsonCategory> result = categoryService.findCategoryList();
		List<JsonCategory> categories = result.getItems();
		modelMap.put("categories", categories);
		modelMap.put("categoryId", categoryId);
		// 商品列表
		PageObject<JsonProduct> productPageResult = productService.findProductPage(pageNo, pageSize, categoryId, 1);
		modelMap.put("productPage", productPageResult.getPage());

		// 购物车
		TempshoppingCart tempShoppingCart = getTempshoppingCart(request, response);
		modelMap.put("tempCart", tempShoppingCart);

		modelMap.put("navFlag", 2);
		return new ModelAndView("shop/shopIndex", modelMap);
	}

	@RequestMapping(value = "/shoppingCart")
	public ModelAndView showShoppingCart(HttpServletRequest request, HttpServletResponse response, ModelMap modelMap) {
		// 购物车
		TempshoppingCart tempShoppingCart = getTempshoppingCart(request, response);
		modelMap.put("tempCart", tempShoppingCart);

		return new ModelAndView("shop/shoppingCart", modelMap);
	}

	@RequestMapping(value = "/addProductToCart.do", method = RequestMethod.POST)
	public void addProductToCart(Long productId, String productName, String smallImage,
			@RequestParam(defaultValue = "1") Integer counts, Long productSkuRelId, HttpServletRequest request,
			HttpServletResponse response) {
		SingleObject<TempshoppingCart> result = new SingleObject<>();
		try {
			TempshoppingCart tempshoppingCart = (TempshoppingCart) request.getSession().getAttribute("shoppingCart");
			List<TempshoppingCartItem> tempshoppingCartItems = null;
			if (tempshoppingCart != null) {
				tempshoppingCartItems = tempshoppingCart.getItems();
			} else {
				tempshoppingCart = new TempshoppingCart();
			}

			if (tempshoppingCartItems == null) {
				tempshoppingCartItems = new ArrayList<>();
			}
			SingleObject<JsonProductSkuRelation> skuRelResult = productSkuRelService
					.findProductSkuRelationById(productSkuRelId);
			JsonProductSkuRelation skuRel = skuRelResult.getObject();
			if (tempshoppingCartItems.isEmpty()) {
				TempshoppingCartItem cartItem = new TempshoppingCartItem();
				cartItem.setCounts(counts);
				cartItem.setProductId(productId);
				cartItem.setProductName(productName);
				cartItem.setValue(skuRel.getPrice()*counts);
				cartItem.setSmallImage(smallImage);
				cartItem.setPrice(skuRel.getPrice());
				cartItem.setProductSkuRelId(productSkuRelId);
				if (skuRel != null) {
					cartItem.setSkuValue1(skuRel.getSkuValue1());
					cartItem.setSkuValue2(skuRel.getSkuValue2());
				}
				tempshoppingCartItems.add(cartItem);
			} else {
				boolean flag = false;// 是否已存在该商品标志
				for (int i = 0; i < tempshoppingCartItems.size(); i++) {
					TempshoppingCartItem cartItem = tempshoppingCartItems.get(i);
					if (cartItem.getProductId().equals(productId)
							&& cartItem.getProductSkuRelId().equals(productSkuRelId)) {
						cartItem.setCounts(cartItem.getCounts() + counts);
						cartItem.setValue(cartItem.getCounts() * skuRel.getPrice());
						tempshoppingCartItems.remove(i);
						tempshoppingCartItems.add(i, cartItem);
						flag = true;
						break;
					}
				}
				if (flag == false) {// 如果不存在，则新增一个
					TempshoppingCartItem cartItem = new TempshoppingCartItem();
					cartItem.setCounts(counts);
					cartItem.setProductId(productId);
					cartItem.setProductName(productName);
					cartItem.setValue(skuRel.getPrice()*counts);
					cartItem.setSmallImage(smallImage);
					cartItem.setPrice(skuRel.getPrice());
					cartItem.setProductSkuRelId(productSkuRelId);
					if (skuRel != null) {
						cartItem.setSkuValue1(skuRel.getSkuValue1());
						cartItem.setSkuValue2(skuRel.getSkuValue2());
					}
					tempshoppingCartItems.add(cartItem);

				}
			}
			Integer totalCounts = 0;
			Double totalValue = 0.00;
			for (TempshoppingCartItem tempshoppingCartItem : tempshoppingCartItems) {
				totalCounts += tempshoppingCartItem.getCounts();
				totalValue += tempshoppingCartItem.getValue();
			}
			tempshoppingCart.setCounts(totalCounts);
			tempshoppingCart.setValue(totalValue);
			tempshoppingCart.setItems(tempshoppingCartItems);

			request.getSession().setAttribute("shoppingCart", tempshoppingCart);
			result.setObject(tempshoppingCart);
			result.setStatusObject(StatusHouse.COMMON_STATUS_OK);
			ResponseUtils.renderJson(response, result);

			Long memberId = getLoginMemberId(request, response);
			if (memberId != null) {
				SingleObject<JsonMember> resultMember = memberService.findMemberById(memberId);
				JsonMember member = resultMember.getObject();
				// 调用接口更新购物车
				JSONArray jsonArray = new JSONArray();
				JSONObject jsonObject = new JSONObject();
				jsonObject.put("productId", productId);
				jsonObject.put("productSkuRelId", productSkuRelId);
				jsonObject.put("counts", counts);
				jsonArray.add(jsonObject);
				shoppingCartService.updateShoppingCart(member.getShoppingCart().getId(),
						JSONArray.toJSONString(jsonArray));
			}
		} catch (ServiceException e) {
			result.setStatusObject(e.getStatusObject());
		} catch (Exception e) {
			e.printStackTrace();
			result.setStatusObject(StatusHouse.COMMON_STATUS_ERROR);
		}

	}

	@RequestMapping(value = "/deleteCartItems.do", method = RequestMethod.POST)
	public void deleteCartItems(String productIds, String productSkuRelIds, HttpServletRequest request,
			HttpServletResponse response) {
		SingleObject<TempshoppingCart> result = new SingleObject<>();
		try {
			String[] productIdsArra = null;
			String[] productSkuRelIdsArra = null;
			if (StrUtils.isNotNULL(productIds) && StrUtils.isNotNULL(productSkuRelIds)) {
				productIdsArra = productIds.split(",");
				productSkuRelIdsArra = productSkuRelIds.split(",");
			}

			TempshoppingCart tempshoppingCart = (TempshoppingCart) request.getSession().getAttribute("shoppingCart");
			List<TempshoppingCartItem> tempshoppingCartItems = null;
			if (tempshoppingCart != null) {
				tempshoppingCartItems = tempshoppingCart.getItems();
			} else {
				tempshoppingCart = new TempshoppingCart();
			}

			if (tempshoppingCartItems == null) {
				tempshoppingCartItems = new ArrayList<>();
			}
			if (!tempshoppingCartItems.isEmpty() && productIdsArra != null && productSkuRelIdsArra != null) {
				List<TempshoppingCartItem> _tempshoppingCartItems = new ArrayList<>();
				for (TempshoppingCartItem tempshoppingCartItem : tempshoppingCartItems) {
					for (int i = 0; i < productIdsArra.length; i++) {
						Long productId = Long.valueOf(productIdsArra[i]);
						Long relId = Long.valueOf(productSkuRelIdsArra[i]);
						if (productId.equals(tempshoppingCartItem.getProductId())
								&& relId.equals(tempshoppingCartItem.getProductSkuRelId())) {
							tempshoppingCart.setCounts(tempshoppingCart.getCounts() - tempshoppingCartItem.getCounts());
							tempshoppingCart.setValue(tempshoppingCart.getValue() - tempshoppingCartItem.getValue());
							_tempshoppingCartItems.add(tempshoppingCartItem);
						} else {

						}
					}

				}
				tempshoppingCartItems.removeAll(_tempshoppingCartItems);
				tempshoppingCart.setItems(tempshoppingCartItems);
			}
			request.getSession().setAttribute("shoppingCart", tempshoppingCart);
			result.setObject(tempshoppingCart);
			result.setStatusObject(StatusHouse.COMMON_STATUS_OK);

			Long memberId = getLoginMemberId(request, response);
			if (memberId != null) {
				SingleObject<JsonMember> memberResult = memberService.findMemberById(memberId);
				JsonMember member = memberResult.getObject();
				if (member != null) {
					shoppingCartService.deleteShoppingCartProduct(member.getShoppingCart().getId(), productIds,
							productSkuRelIds);
				}
			}
		} catch (ServiceException e) {
			result.setStatusObject(e.getStatusObject());
		} catch (Exception e) {
			e.printStackTrace();
			result.setStatusObject(StatusHouse.COMMON_STATUS_ERROR);
		}
		ResponseUtils.renderJson(response, result);
	}

}
